let App = getApp();
// import html2json from '../../utils/html2json';
Component({
  properties: {
    myProperty: {
      type: Number,
      value: '1'
    },
    dataIndex:{
      type: Number,
      value:0
    },
    api:{
      type:String,
      value:'/mapi/source/index'
    }
  },
  data: {
    searchColor: "rgba(0,0,0,0.4)",
    searchSize: "15",
    searchName: "搜索",
    scrollHeight: null,
    showView: false,
    arrange: "",
    sortPrice: false,   // 价格从低到高
    orderType: '',
    option: {},
    list: [],
    noList: true,
    no_more: false,
    first_array: [],
    first_value:[],
    index: 0,
    sindex:0,
    id:0,
    sid:0,
    second_array:[],
    second_value:[],
    pageNumber: 1,
  },
  lifetimes: {
    attached(option) {
      let _this = this;
      // 获取一级分类
      App._get('/mapi/category/index', { pid: 1 }, function(result) {
        console.log(result)
        result.data.unshift({ id: 0, title: '全部素材' })
        const list = result.data.map((item) => {
          return item.title
        })
        console.log(result.data)
        setTimeout( async () => {
          await _this.setData({'first_array': list, 'first_value': result.data ,index:_this.data.dataIndex==-1?0:_this.data.dataIndex})
          _this.bindPickerChange({detail:{value:_this.data.dataIndex}})
          _this.getProductList(true)
        }, 100);
      
       
      })

      // 设置商品列表高度
      _this.setListHeight();

      // 记录option
      _this.setData({  }, function() {
        // 获取商品列表
        _this.getProductList(true);
      });
    }
  },
  methods: {

    bindPickerChange(e) {
    
      const _this = this

      this.setData({
        index: e.detail.value==-1?0:e.detail.value
      })
      // 查询二级分类
      console.log(this.data.first_value[e.detail.value==-1?0:e.detail.value])
      if (this.data.first_value[e.detail.value].children) {
        const list = this.data.first_value[e.detail.value].children.map(item => item.title)
        const list_value = [...this.data.first_value[e.detail.value].children]
        list.unshift('全部')
        list_value.unshift({ id: 0, title: '全部素材' })
        this.setData({ 'second_array': list, second_value: list_value, sindex: 0 })
      }
      this.setData({ 'id': this.data.first_value[e.detail.value].id })
      this.getProductList(true)

    },
    sbindPickerChange(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      const id = this.data.second_value[e.detail.value].id
      this.setData({
        sindex: e.detail.value,
        sid: id
      })
      this.getProductList(true)
    },
      /**导航菜单的跳转路径**/
  goNav(event) {
    // 跳转商品分类的id
    let id = event.currentTarget.dataset.id;
    let url = '../../pages/product/detail?id=' + id;
    wx.navigateTo({
      url: url,
    })
  },
    getProductList(is_super, pageNumber) {
      let _this = this;
      console.log('success：' + _this.data.orderType);
      console.log('success:' + _this.data.option.search);
      App._post(this.data.api, {
        page: pageNumber || 1,
        category_id_2: _this.data.id,
        category_id_3: _this.data.sid,
        flag: _this.data.myProperty,
        search: _this.data.searchValue || '',
        token:wx.getStorageSync('token')
      }, function(result) {
        let resultList = result.data
          , dataList = _this.data.list;
        console.log(is_super, 'is')
        // result.data.forEach(item => {
        //   item.title = html2json(item.title); // 修改每个元素的 title 属性
        // });
        if (is_super) {
          _this.setData({ 'list': resultList });
        } else {
          _this.setData({ 'list': dataList.concat(resultList) });
        }
      });
    },
    getSearchContent(e) {
      this.data.searchValue = e.detail.value;

    },
    setListHeight() {
      let _this = this;
      wx.getSystemInfo({
        success: function(res) {
          _this.setData({
            scrollHeight: _this.data.myProperty == 1 ? res.windowHeight - 60 : res.windowHeight-263,
          });
        }
      });
    },
    switchSortType(e) {
      let _this = this
        , orderType
        , newSortType = e.currentTarget.dataset.type
        , newSortPrice = newSortType === 'price' ? !_this.data.sortPrice : true;

      if (newSortType === 'price') {
        orderType = newSortPrice ? 'PRICE_ASC' : 'PRICE_DESC';
      } else if (newSortType === 'sales') {
        orderType = 'SALES_DESC';
      } else {
        orderType = 'TOP_DESC';
      }

      _this.setData({
        list: {},
        pageNumber: 1,
        sortPrice: newSortPrice,
        orderType: orderType
      }, function() {
        // 获取商品列表
        _this.getProductList(true);
      });
    },
    onChangeShowState() {
      let _this = this;
      _this.setData({
        showView: !_this.data.showView,
        arrange: _this.data.arrange ? "" : "arrange"
      });
    },
    bindDownLoad() {
      // 已经是最后一页
      if (this.data.pageNumber >= this.data.lastPage) {
        this.setData({ no_more: true });
        return false;
      }
      this.getProductList(false, ++this.data.pageNumber);
    },
    onShareAppMessage() {
      return {
        title: "阿斯顿",
        desc: "",
        path: "/pages/search/index"
      };
    },
    setlike(event) {
      console.log(event, '--event')
      const _this = this
      const source_id = event.currentTarget.dataset.source_id
      const index = event.currentTarget.dataset.index
      console.log(source_id, '--source_id')
      App._get('/mapi/user_operate/dolike', { source_id: source_id }, function(result) {
        if (result.code == 200) {
          const products = _this.data.list;
          if (products[index].user_like_state == 0) {
            products[index].like_num += 1;
            products[index].user_like_state = 1
            _this.setData({
              list: products
            });
            wx.showToast({
              title: '点赞成功',
            })
          } else {
            products[index].like_num -= 1;
            products[index].user_like_state = 0;
            _this.setData({
              list: products
            });
            wx.showToast({
              title: '取消点赞',
            })
          }
        } else {
          // 请登录
          App.doLogin()

        }
      })
    },
    setcollect(event) {
      const _this = this
      const source_id = event.currentTarget.dataset.source_id
      const index = event.currentTarget.dataset.index
      App._get('/mapi/user_operate/docollect', { source_id: source_id }, function(result) {
        if (result.code == 200) {
          const products = _this.data.list;
          if (products[index].user_collect_state == 0) {
            products[index].collect_num += 1;
            products[index].user_collect_state = 1
            _this.setData({
              list: products
            });
            wx.showToast({
              title: '收藏成功',
            })
          } else {
            products[index].collect_num -= 1;
            products[index].user_collect_state = 0;
            _this.setData({
              list: products
            });
            wx.showToast({
              title: '取消收藏',
            })
          }
        } else {
          App.doLogin()
        }
      })
    },
    async download(event) {
      const index = event.currentTarget.dataset.index;
      const type = this.data.list[index].type;
      const file = this.data.list[index].content;
      const text = this.data.list[index].title;
      // 复制文本
      App.copyText(text);
      // 创建一个包含所有下载任务的 Promise 数组
      const downloadPromises = file.map(element => App.download(element, type));
    
      try {
        // 使用 Promise.all 并行处理所有下载任务
        await Promise.all(downloadPromises);
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      } catch (error) {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
        console.error('保存失败', error);
      }
    },
    preview(event) {
      const src = event.currentTarget.dataset.src
      const url = event.currentTarget.dataset.url
      wx.previewImage({
        current:this.data.list[src].content[url],
        urls: this.data.list[src].content,
      })
    }
  }
});
